package cn.b.training.baby_education_training.service.impl;

import cn.b.training.baby_education_training.security.SmsCodeStore;
import cn.b.training.baby_education_training.security.TokenService;
import cn.b.training.baby_education_training.service.SmsService;
import cn.b.training.baby_education_training.service.UserInfoService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @program: baby_education
 * @description
 * @author: wuying
 * @create: 2022-11-29 11:25
 **/
@Service
public class SmsServiceImpl implements SmsService {

    @Value("${sms.aliyun.accessKeyId}")
    String accessKeyId;
    @Value("${sms.aliyun.accessKeySecret}")
    String accessKeySecret;
    @Value("${sms.aliyun.signName}")
    String signName;
    @Value("${sms.aliyun.templateCode}")
    String templateCode;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private TokenService tokenService;

    /**
     * 发送短信验证码
     * @param phone 手机号码
     * @return
     */
    @Override
    public boolean sendValidateSms(String phone) {
        //获得6位长度的验证码
        String code = this.getRandomCode(6);
        //如果映射表中有该手机号码的验证码记录，直接使用此验证码重新发送。
        if (SmsCodeStore.codeStore.containsKey(phone)){
            code=SmsCodeStore.codeStore.get(phone);
        }
        try {
            //调用初始化客户端方法，得到阿里云调用客户端对象
            Client smsClient = this.getClient(accessKeyId,accessKeySecret);
            //发送短信验证码请求：参数内容具体参考阿里云短信服务开发文档
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    //手机号码
                    .setPhoneNumbers(phone)
                    //短信服务签名
                    .setSignName(this.signName)
                    //短信模板
                    .setTemplateCode(this.templateCode)
                    //短信内容参数，将验证码填入短信
                    .setTemplateParam("{\"code\":\""+code+"\"}");
            //发送短信
            smsClient.sendSms(sendSmsRequest);
            //短信发送成功后，将手机号与验证码写入映射表
            SmsCodeStore.codeStore.put(phone,code);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean validateSms(String phone, String code) {
        if (SmsCodeStore.codeStore.containsKey(phone)){
            //从映射表中读出正确验证码
            String correctCode = SmsCodeStore.codeStore.get(phone);
            //如果验证码与输入验证码一致，验证通过
            if (correctCode.equals(code)){
                //验证通过，需要将手机号码从映射表中移除。
                SmsCodeStore.codeStore.remove(phone);
                return true;
            }
        }
        return false;
    }

    /**
     * 随机产生指定位数的数字
     */
    private String getRandomCode(Integer length){
        String code="";
        Random r=new Random();
        for (int i=0;i<length;i++){
            code+=String.valueOf(r.nextInt(10));
        }
        return code;
    }

    /**
     * 获取阿里云客户端
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    private Client getClient(String accessKeyId, String accessKeySecret) throws Exception{
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}
